﻿using System.Linq;
using System.Web.Mvc;
using Church.Entities;
using Church.Resources;
using MvcContrib;

namespace Church.Controllers
{
	public class ShrinesController : Controller
	{
		#region Actions

		public ActionResult Index()
		{
			var path = HttpContext.Server.MapPath(AppConfig.ShrinesDataFilePath);
			var model = AppContext.XmlSerializerService.Deserialize<ShrinesCollection>(path);
			if (model != null && model.Shrines != null)
				model.Shrines = model.Shrines.OrderBy(s => s.Number).ToList();
			return View(model);
		}

		public ActionResult Shrine(int number)
		{
			XmlElementShrine model;
			FillShrineModel(out model, number);
			if (model == null)
				return this.RedirectToAction(action => action.Index());
			return View(model);
		}

		#endregion

		#region Internal Implementation

		private void FillShrineModel(out XmlElementShrine model, int number)
		{
			model = null;
			var path = HttpContext.Server.MapPath(AppConfig.ShrinesDataFilePath);
			var data = AppContext.XmlSerializerService.Deserialize<ShrinesCollection>(path);
			if (data != null && data.Shrines != null)
				model = data.Shrines.SingleOrDefault(s => s.Number == number);
		}

		#endregion
	}
}
